<template>
  <div>
    <Card class="card clear-float">
      <p class="card-title" slot="title">{{$t('login_rule_manage')}}</p>
      <div class="operate-area">
        <div class="inline-item search-item">
          <Button
            type="primary"
            icon="md-add"
            @click="addItem"
            :style="{ marginRight: '10px' }"
            >{{$t('0QK34KQN7OjBxetSabcS1')}}</Button
          >
          <!-- <Button
            type="error"
            @click="deleteItems"
            :style="{ marginRight: '10px' }"
            >{{$t('hND4KLgCabT6swtTJBIUf')}}</Button
          >
          <Button type="info" @click="setRole">{{$t('gDsSHie0lGvhFGkepWLIS')}}</Button> -->
        </div>
      </div>
      <Table
        highlight-row
        :loading="loading"
        :columns="columns"
        :data="data"
      >
      </Table>
      <!-- <Page
        class="page-component"
        size="small"
        :total="total"
        show-sizer
        show-elevator
        show-total
        :current.sync="current"
        :page-size="pageSize"
        :page-size-opts="pageSizeOpts"
        @on-change="changePage"
        @on-page-size-change="changePageSize"
      ></Page> -->
    </Card>
    <Modal
      v-model="modal"
      :title="(status === 'new' ? $t('N8xdbBoV-d6Vc33tKrGGm') : $t('3cH_U2GeBUW1V74W8oDNv')) + $t('Bp-VSE3SuRvMKppg6_O6o')"
      footer-hide
      :mask-closable="false"
    >
      <form-info
        :data="formData"
        :rules="rules"
        :status="status"
        :open="modal"
        @success="success"
        @fail="fail"
        @close="close"
      />
    </Modal>
    <Modal
      v-model="roleModal"
      :title="formTitle"
      footer-hide
      :mask-closable="false"
    >
      <menu-role
        :show="roleModal"
        :selectRoles="selectRoles"
        @save="save"
        @cancel="cancel"
      ></menu-role>
    </Modal>
  </div>
</template>

<script>
import {
  getAdminRoleList,
  updateAdminRoleList,
  getUserRoleList,
  updateUserRole,
  deleteRole
} from '@/api/data2'
import FormInfo from './component/user-role-form-info'
import MenuRole from '@/cuscomponents/menurole'

export default {
  name: 'login_rule_manage',
  components: {
    FormInfo,
    MenuRole
  },
  data () {
    return {
      loading: false,
      modal: false,
      roleModal: false,
      formData: {
        name: '',
        parentName: this.$store.state.user.userName,
        desc: '',
        operatorid: this.$store.state.user.operatorId,
        stationid: this.$store.state.user.stationId,
        menuidlist: []
      },
      rules: {
        name: [{ required: true, message: this.$t('BPlIRlxNYYQBs-86zjYBP'), trigger: 'blur' }]
      },
      columns: [
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: this.$t('nm-H-HADPIPxcd4ShO9ez'),
          key: 'name',
          width: 300
        },
        {
          title: this.$t('agt'),
          key: 'isoperatormanager',
          render: (h, params) => {
            const { operatorid, stationid } = params.row
            if (operatorid != 0 && stationid == 0) {
              return h(
                'Tag',
                {
                  props: {
                    color: 'success'
                  }
                },
                ['√']
              )
            } else {
              return h(
                'Tag',
                {
                  props: {
                    color: 'error'
                  }
                },
                ['×']
              )
            }
          }
        },
        {
          title: this.$t('SWJNpRnfSDK7MAg0omTmr'),
          key: 'isstationmanager',
          render: (h, params) => {
            const { operatorid, stationid } = params.row
            if (operatorid != 0 && stationid != 0) {
              return h(
                'Tag',
                {
                  props: {
                    color: 'success'
                  }
                },
                ['√']
              )
            } else {
              return h(
                'Tag',
                {
                  props: {
                    color: 'error'
                  }
                },
                ['×']
              )
            }
          }
        },
        {
          title: this.$t('Ty1ns2epHIaihi82jwUfc'),
          width: 280,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    icon: 'ios-settings'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.setRole(params.index)
                    }
                  }
                },
                this.$t('gDsSHie0lGvhFGkepWLIS')
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'success',
                    size: 'small',
                    icon: 'ios-create'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.editItem(params.index)
                    }
                  }
                },
                this.$t('3cH_U2GeBUW1V74W8oDNv')
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small',
                    icon: 'ios-trash'
                  },
                  style: {
                    // marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.deleteItems(params.index)
                    }
                  }
                },
                this.$t('hND4KLgCabT6swtTJBIUf')
              )
            ])
          }
        }
      ],
      data: [],
      total: 10,
      current: 1,
      pageSize: 5,
      pageSizeOpts: [5, 10, 15, 20],
      status: 'new',
      editIndex: 0
    }
  },
  created () {
    this.queryTable()
  },
  computed: {
    selectRoles () {
      const menulist = this.data[this.editIndex]?.menulist
      if (menulist) {
        return menulist.map(m => m.id)
      }
      return []
    },
    isAdmin () {
      return this.$store.getters.isAdmin
    },
    formTitle () {
      return this.$t('3cH_U2GeBUW1V74W8oDNv') + '(' + (this.data[this.editIndex] ? this.data[this.editIndex].name : '') + ')' + this.$t('R0n24Zv9Aegrwzt9vHwKS')
    }
  },
  methods: {
    searchTable () {
      this.queryTable()
    },
    changeTime () {
      this.queryTable()
    },
    async queryTable ({
      current = this.current,
      pageSize = this.pageSize
    } = {}) {
      this.loading = true
      const { code, data, desc } = this.isAdmin
        ? await getAdminRoleList()
        : await getUserRoleList()
      if (code == 200) {
        this.data = data.datalist || []
      } else {
        this.$Message.error(desc)
      }
      // this.data = res.tableData
      // this.total = res.total
      this.loading = false
    },
    changePage (num) {
      this.current = num
      this.queryTable()
    },
    changePageSize (num) {
      this.pageSize = num
      this.queryTable()
    },
    addItem () {
      this.formData = {
        name: '',
        parentName: this.$store.state.user.userName,
        desc: '',
        operatorid: this.$store.state.user.operatorId,
        stationid: this.$store.state.user.stationId,
        menuidlist: []
      }
      this.status = 'new'
      this.modal = true
    },
    editItem (index) {
      const item = this.data[index]
      const { menulist, ...other } = item
      this.formData = _.assign({
        parentName: this.$store.state.user.userName,
        desc: ''
      }, {
        ...other,
        menuidlist: menulist || []
      }
      )
      this.editIndex = index
      this.status = 'edit'
      this.modal = true
    },
    deleteItems (index) {
      this.$Modal.confirm({
        title: this.$t('oiW2WYZoyJSt3j7yCy10e'),
        content: this.$t('KePcPzUJR7hEB6lp4nEtV'),
        onOk: async () => {
          const { code, desc } = await deleteRole({
            name: this.data[index].name,
            id: this.data[index].id
          })
          if (code == 200) {
            this.$Message.success(desc || this.$t('X3B4zUoYLLk9A5CKgzmbn'))
            this.queryTable()
          } else {
            this.$Message.error(desc)
          }
        }
      })
    },
    success (desc) {
      if (this.status === 'new') {
        this.$Message.success(desc || this.$t('Hsf3TzqX4ktuzZVNmVHMe'))
      } else {
        this.$Message.success(desc || this.$t('rJ9uXBlTbaC-gCrMJyhCy'))
      }
      this.modal = false
      this.queryTable()
    },
    fail (msg) {
      this.modal = false
      this.$Message.error(msg)
    },
    close () {
      this.modal = false
    },
    setRole (index) {
      this.editIndex = index
      this.roleModal = true
    },
    async save (result) {
      console.log('=== save result', result)
      this.roleModal = false
      const { menulist, ...other } = this.data[this.editIndex]
      const { code, data, desc } = this.isAdmin
        ? await updateAdminRoleList(
          _.assign({}, other, { menuidlist: result })
        )
        : await updateUserRole(
          _.assign({}, other, { menuidlist: result })
        )
      if (code == 200) {
        this.$Message.success(this.$t('MEC_ylZjCpu_iRnh4dsvV'))
        this.queryTable()
      } else {
        this.$Message.error(desc)
      }
    },
    cancel () {
      this.roleModal = false
    }
  }
}
</script>
